using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

using OWED.Network.Messages.Reply;
using OWED.Network.Messages.General;

using NUnit.Framework;

namespace OWED.Network.Messages
{
	[TestFixture]
	public class TestDocumentSend
	{
		[Test]
		public void TestSendingDocument()
		{
			DocumentServer serv = new DocumentServer(4432);
			Connection c = new Connection("localhost", 4432);

			PassFail login = MessageGet.GetFromXml(c.Send(
				new Login(new User("chris"), new Password("pass")).ToXml())) as PassFail;
			Assert.IsNotNull(login, "failed to get login reply correctly!");
			Assert.IsTrue(login.pass, login.Reason.Value);


			DocumentReply doc = MessageGet.GetFromXml(
                c.Send(
                    new GetDocument(new User("chris"), new DocName("THE_DOCUMENTS_NAME")
                                            , new DocVersion(5)).ToXml()
                )
            ) as DocumentReply;
			Assert.IsNotNull(doc, "failed to get document properly");
			Console.WriteLine(doc.ADocument.GetDocument().InnerXml);

			c.Dispose();
			serv.Dispose();
		}

		class DocumentServer : Server
		{
			public DocumentServer(int port) : base(port) { }

			protected override void ConnectionLoop(object me)
			{
				Login l = Wait(me) as Login;
				if (l == null) {
					PassFail p = new PassFail(false, 
						new Reason(1, "First message not a login"));
					Reply(me, p);
					return;
				}

				/*if (l.User.name != "chris" || l.User.pass != "pass") {
					PassFail p = new PassFail(false, 
						new Reason(2, "Wrong username or password"));
					Reply(me, p);
					return;
				}*/

				Reply(me,
					new PassFail(true, 
					new Reason(0, "Login successful")));

                Console.WriteLine("Doing the document stuffs:");

				GetDocument docrequest = Wait(me) as GetDocument;
				XmlDocument thedoc = new XmlDocument();
				thedoc.LoadXml("<book><chapter><para>This is a paragraph</para></chapter></book>");
				DocumentReply reply = new DocumentReply(
					new ADocument(thedoc, docrequest.DocName));
                Console.WriteLine("---\nServer sends:\n\n");
                Console.WriteLine(reply.ToXml().OuterXml);
                Console.WriteLine("\n----\n");
				Reply(me, reply);
			}
		}

	}
}
